// 实现锁

#pragma once

#include <iostream>
#include <pthread.h>

namespace MutexModel
{
    class Mutex
    {
    public:
        Mutex()
        {
            // 创建锁
            pthread_mutex_init(&_mutex, nullptr);
        }

        void Lock()
        {
            pthread_mutex_lock(&_mutex);
        }
        void Unlock()
        {
            pthread_mutex_unlock(&_mutex);
        }

        ~Mutex()
        {
            pthread_mutex_destroy(&_mutex);
        }

        pthread_mutex_t *Get()
        {
            return &_mutex;
        }

    private:
        pthread_mutex_t _mutex; // 锁类型
    };

    // RAII 写法
    class LockGuard
    {
    public:
        LockGuard(Mutex &mutex)
            : _lock(mutex)
        {
            _lock.Lock();
        }
        ~LockGuard()
        {
            _lock.Unlock();
        }

    private:
        Mutex _lock; // 构造自动创建锁 , 析构自动销毁锁
    };

}